// packageI/public_welfare_fund/publicWelfare/publicWelfare.js
const echarts = require("../../../ec-canvas/echarts"); //路径一定要正确否则会调用错误
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    charts_type: "1",
    listType: "0",
    activeDate: "0",
    dateList: [{
      type: "0",
      title: "全部"
    },
    {
      type: "1",
      title: "今日"
    },
    {
      type: "2",
      title: "昨日"
    },
    {
      type: "3",
      title: "本周"
    },
    {
      type: "4",
      title: "上周"
    },
    {
      type: "5",
      title: "本月"
    }
    ],

    Height: 0,
    LastHeight: 0,

    finished: false,
    loading: false,
    page: 1,

    is_expend_member: "",
    hasSwipeImage: false,
    swipers: {},
    extension: {},
    chartsData: {},

    personnelList: [],
    expendList: [],
    orderList: [],
  
    language: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  onShow: function () {
    this.getData();
  },

  getData() {
    let urlStr = app.getNetAddresss("plugin.public-fund.frontend.controllers.fund.index");
    wx.showLoading({title: 'loading',})
    app._getNetWork({
      url: urlStr,
      data: {
        page: 1,
        date_type: this.data.activeDate
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.result !== 1) {
          wx.showToast({ title: res.data.msg});
          return;
        }

        let data = res.data.data;
        let { is_expend_member, set, head, middle, bottom } = data;
        let isEmpty = set ? Object.values(set).some(item => item.thumb) : false;
        this.setData({
          is_expend_member: is_expend_member,
          hasSwipeImage: isEmpty,
          swipers: set,
          extension: head,
          chartsData: middle,
          personnelList: bottom.fund_human_list.data,
        })
        let bottomData = bottom.fund_human_list;
        if (bottomData.current_page >= bottomData.last_page || bottomData.data.length < bottomData.per_page) {
          this.setData({finished: true});
        }
        if (this.data.charts_type == 1) {
          this.initEcharts();
        } else {
          this.initPieEcharts();
        }
      },
      
    });
  },

  changeDate (event) {
    let index = event.currentTarget.dataset.index;
    if (index == this.data.activeDate) return;
    this.setData({activeDate: index});

    this.initLoad();
    if (this.data.listType == 0) {
      this.getData();
    } else {
      this.getData();
      this.getOrderData(this.data.listType);
    }
  },

  clickExtension(event) {
    let key = event.currentTarget.dataset.index;
    if (key == "amount_total" || key == "order_total") {
      this.scrollAnchor("1");
    } else if (key == "surplus_amount_total") {
      wx.navigateTo({
        url: '/packageI/public_welfare_fund/record/record?type=' + 2,
      })
    } else if (key == "expend_amount_total" || key == "expend_times_total") {
      this.scrollAnchor("2");
    } else if (key == "member_total") {
      this.scrollAnchor("0");
    }
  },

  clickMemberAvatar (event) {
    this.memberId = event.detail;
    this.scrollAnchor('1');
  },

  scrollAnchor(index) {
    let scrollBackcall = function () {
      wx.createSelectorQuery().select('.list-box').boundingClientRect(res => {
        wx.pageScrollTo({
          scrollTop: res.top,
          duration: 300 //滚动所需时间 如果不需要滚动过渡动画，设为0（ms）
        })
      }).exec()
    };
    
    if (this.data.listType != index) {
      this.setData({listType: index});
      // this.changeListType(scrollBackcall);
    } else {
      scrollBackcall();
    }
  },

  toRecord() {
    wx.navigateTo({
      url: '/packageI/public_welfare_fund/record/record?type=' + 1,
    })
  },

  toDonations() {
    wx.navigateTo({
      url: '/packageI/public_welfare_fund/donations/donations',
    })
  },

  setListType (e) {
    this.setData({listType: e.detail.name});
    this.changeListType();
  },

  changeListType(scrollBackcall) {
    this.initLoad();
    if (this.data.listType == 0) {
      this.getPersonnelData(scrollBackcall);
    } else {
      this.getOrderData(this.data.listType, scrollBackcall);
    }
  },

  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = winWid * imgh / imgw + "px"; //等比设置swiper的高度。 即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    if (parseInt(swiperH) > this.data.LastHeight) {
      this.setData({
        Height: swiperH, //设置高度
      });
      this.data.LastHeight = parseInt(swiperH);
    }
  },

  // 公益人员列表
  getPersonnelData(scrollBackcall) {
    if (this.data.finished || this.data.loading) {
      return false;
    }
    this.setData({loading: true});
    let urlStr = app.getNetAddresss("plugin.public-fund.frontend.controllers.fund.index");
    app._getNetWork({
      url: urlStr,
      data: {
        page: this.data.page,
        date_type: this.data.activeDate
      },
      success: (res) => {
        if (res.data.result !== 1) {
          wx.showToast({ title: res.data.msg});
          return;
        }

        let { bottom } = res.data.data;
        let data = bottom.fund_human_list;
        if (data.current_page >= data.last_page || data.data.length < data.per_page) {
          this.setData({finished: true});
        }
        let dataList = this.data.page > 1 ? this.data.personnelList.concat(data.data) : data.data;
        this.setData({
          personnelList: dataList,
          page: ++this.data.page
        })
        typeof scrollBackcall === "function" ? scrollBackcall() : "";
      },
      complete: () => {
        this.setData({loading: false})
      }
    });
  },

  // 公益支出，公益订单
  getOrderData(changeType, scrollBackcall) {
    if (this.data.finished || this.data.loading) {
      return false;
    }
    this.setData({loading: true});

    let urlStr = app.getNetAddresss("plugin.public-fund.frontend.controllers.fund.amountList");
    app._getNetWork({
      url: urlStr,
      data: {
        page: this.data.page,
        member_id: this.memberId,
        date_type: this.data.activeDate,
        change_type: changeType
      },
      success: (res) => {
        if (res.data.result !== 1) {
          wx.showToast({ title: res.data.msg});
          return;
        }

        let data = res.data.data ? res.data.data.list : {};
        if (data.current_page >= data.last_page || data.data.length < data.per_page) {
          this.setData({finished: true});
        }

        if (changeType == 1) {
          this.setData({
            orderList: this.data.page > 1 ? this.data.orderList.concat(data.data) : data.data,
            page: ++this.data.page
          })
        } else {
          this.setData({
            expendList: this.data.page > 1 ? this.data.expendList.concat(data.data) : data.data,
            page: ++this.data.page
          })
        }
        typeof scrollBackcall === "function" ? scrollBackcall() : "";
      },
      complete: () => {
        this.memberId = '';
        this.setData({loading: false})
      },
    });
  },

  tabChange(e)  {
    this.setData({charts_type: e.detail.name});
    if (this.data.charts_type == 1) {
      this.initEcharts();
    } else {
      this.initPieEcharts();
    }
  },

  initEcharts() {
    let echartsComponnet = this.selectComponent("#echats-income");
    let income = this.data.chartsData.income;
    console.log(this.data.chartsData)
    let totals = income.map(item => item.count);
    let maxCount = Math.max(...totals) || 50;
    let option = {
      tooltip: {
        trigger: "axis"
      },
      grid: {
        right: "6%",
        left: "6%",
        bottom: "5%",
        containLabel: true
      },
      legend: {
        data: ["金额", "笔数"]
      },
      xAxis: [
        {
          type: "category"
        }
      ],
      yAxis: [
        {
          type: "value",
          name: "金额",
          min: 0
          // max: maxMoney,
          // interval: intervalMoney
        },
        {
          type: "value",
          name: "笔数",
          min: 0,
          max: maxCount,
          axisLabel: {
            formatter: function(value, index) {
              return Math.floor(value);
            }
          }
        }
      ],
      dataset: {},
      series: [
        {
          name: "金额",
          type: "bar",
          color: "#3b84f2",
          barWidth: 20
        },
        {
          name: "笔数",
          type: "line",
          yAxisIndex: 1,
          color: "#ffc11e"
        }
      ]
    };
    option.dataset.dimensions = ["date", "amount", "count"];
    option.dataset.source = income;

    echartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height,
      });
      Chart.setOption(option);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },
  initPieEcharts() {
    let echartsComponnet = this.selectComponent("#echats-income-pie");
    let expend = this.data.chartsData.expend;
    let option = {
      color: ["#3776e7", "#55c3f3"],
      title: {
        x: 50,
        y: "69%",
        text: "",
        textStyle: {
          //主标题的属性
          fontSize: 12, //大小
          fontWeight: 400 //
        }
      },
      legend: {
        type: "plain",
        orient: "vertical",
        x: 20,
        y: "bottom",
        formatter: function(a) {
          let target = expend.find(item => item.name == a);
          return `${a}：${target.amount}元`;
        }
      },
      series: [
        {
          type: "pie",
          radius: ["50%", "60%"],
          center: ["50%", "38%"],
          labelLine: {
            normal: {
              length: 5
            }
          },
          label: {
            position: "outer",
            alignTo: "edge",
            margin: 10,
            formatter: function(a, b, c) {
              return a.name + '\n' + a.percent + "%";
            }
          },
          data: []
        }
      ]
    };
    option.title.text = "收入总额：" + expend[2].amount + "元";
    option.series[0].data = expend.slice(0, 2).map(item => {
      return {
        name: item.name,
        value: parseFloat(item.amount.replace(",", ""))
      };
    });

    echartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height,
      });
      Chart.setOption(option);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },

  onReachBottom: function () {
    if (this.data.listType == 0) {
      this.getPersonnelData();
    } else {
      this.getOrderData(this.data.listType);
    }
  },

  jumpLink (event) {
    console.log(event.currentTarget.dataset)
    let link =  event.currentTarget.dataset.link;
    if (!link) return false;
    wx.reLaunch({
      url: link,
    })
  },

  initLoad() {
    this.setData({
      page: 1,
      finished: false,
      loading: false
    })
  },

  onShareAppMessage: function () {

  },

  onShareTimeline: function () {

  },
});